from math import log
import operator

# 构造数据集
def createDataSet():
    dataSet = [[1, 1, 'yes'],
               [1, 1, 'yes'],
               [1, 0, 'no'],
               [0, 1, 'no'],
               [0, 1, 'no']]                # 数据集
    labels = ['no surfacing','flippers']    # 特征名
    #change to discrete values
    return dataSet, labels

# 计算给定数据的香农熵
def calcShannonEnt(dataSet):
    numEntries = len(dataSet)   # 计算数据集中的实例总数
    labelCounts = {}
    # 为所有可能的分类创建字典，并统计不同类别出现的次数
    for featVec in dataSet: #the the number of unique elements and their occurance
        currentLabel = featVec[-1]   # 读取最后一列的数值
        if currentLabel not in labelCounts.keys(): labelCounts[currentLabel] = 0
        labelCounts[currentLabel] += 1
    shannonEnt = 0.0        # 初始化香浓熵
    # 计算每个类别出现的频率，并累加求得香浓熵
    for key in labelCounts:
        prob = float(labelCounts[key])/numEntries       # 计算概率
        shannonEnt -= prob * log(prob,2)                # 以2为底的对数
    return shannonEnt

# 按照给定特征划分数据集    
def splitDataSet(dataSet, axis, value):
    retDataSet = []         # 为不修改原始数据集，创建一个新的list对象
    # 提取符合要求的值
    for featVec in dataSet:
        if featVec[axis] == value:
            reducedFeatVec = featVec[:axis]     #chop out axis used for splitting
            reducedFeatVec.extend(featVec[axis+1:])
            retDataSet.append(reducedFeatVec)
    return retDataSet

# 选择最好的数据集划分方式    
def chooseBestFeatureToSplit(dataSet):
    numFeatures = len(dataSet[0]) - 1       # 读取数据集的特征数，因为最后一列为标签列，所以需要-1
    baseEntropy = calcShannonEnt(dataSet)   # 计算原始香农熵baseEntropy
    bestInfoGain = 0.0; bestFeature = -1    # 初始化信息增益和最佳划分的特征
    for i in range(numFeatures):            # 遍历所有特征
        featList = [example[i] for example in dataSet]#create a list of all the examples of this feature
        uniqueVals = set(featList)          # 获取当前特征的所有唯一属性值
        newEntropy = 0.0
        # 遍历当前特征的所有唯一属性值，对每个唯一属性值划分依次数据集
        for value in uniqueVals:
            subDataSet = splitDataSet(dataSet, i, value)
            prob = len(subDataSet)/float(len(dataSet))      # 计算当前特征每个唯一属性值划分所占的比例
            newEntropy += prob * calcShannonEnt(subDataSet) # 计算按当前特征划分后数据集的新熵值     
        infoGain = baseEntropy - newEntropy     # 计算按当前特征划分后数据集的信息增益
        if (infoGain > bestInfoGain):       # 将按当前特征划分后数据集的信息增益与bestInfoGain作比较
            bestInfoGain = infoGain         
            bestFeature = i                 # 将信息增益值最大的特征保存在bestFeature中
    return bestFeature                      # 返回bestFeature

# 返回出现次数最多的类别标签
def majorityCnt(classList):
    classCount={}
    for vote in classList:
        if vote not in classCount.keys(): classCount[vote] = 0
        classCount[vote] += 1
    sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)
    return sortedClassCount[0][0]

# 创建树的函数代码
def createTree(dataSet,labels):
    # 创建classList的列表变量，其中包含了数据集的所有类标签
    classList = [example[-1] for example in dataSet]
    if classList.count(classList[0]) == len(classList): 
        return classList[0]     # 类别完全相同则停止继续划分，返回该划分的类别标签
    if len(dataSet[0]) == 1:    # stop splitting when there are no more features in dataSet
        return majorityCnt(classList)   # 遍历完所有特征时返回出现次数最多的类别标签
    bestFeat = chooseBestFeatureToSplit(dataSet)    # 计算最好的数据集划分方式
    bestFeatLabel = labels[bestFeat]                # 根据划分方式获取对应特征名
    myTree = {bestFeatLabel:{}}                     # 构建树
    # 得到当前特征下包含的所有属性值
    del(labels[bestFeat])
    featValues = [example[bestFeat] for example in dataSet]
    uniqueVals = set(featValues)
    # 遍历当前选择特征包含的所有属性值，在每个数据集划分上递归调用函数createTree()
    for value in uniqueVals:
        subLabels = labels[:]       # copy all of labels, so trees don't mess up existing labels
        myTree[bestFeatLabel][value] = createTree(splitDataSet(dataSet, bestFeat, value),subLabels)
    return myTree                            

# 使用决策树的分类函数    
def classify(inputTree,featLabels,testVec):
    firstStr = list(inputTree.keys())[0]    # 获取字典中的第一个关键字
    secondDict = inputTree[firstStr]        # 获取二级字典
    featIndex = featLabels.index(firstStr)  # 将标签字符串转换为索引
    key = testVec[featIndex]
    valueOfFeat = secondDict[key]
    if isinstance(valueOfFeat, dict): 
        classLabel = classify(valueOfFeat, featLabels, testVec)     # 递归
    else: classLabel = valueOfFeat
    return classLabel

# 使用pickle模块存储决策树
def storeTree(inputTree,filename):
    import pickle
    fw = open(filename,'w')
    pickle.dump(inputTree,fw)
    fw.close()
    
def grabTree(filename):
    import pickle
    fr = open(filename)
    return pickle.load(fr)
    
